import userTpl from '../views/user.html'
import handlerbar from 'handlebars';

class UserController {
	constructor() {
		this.userdata = {
			username: '',
			//判断是否是登录状态
			islogin: false,
			//判断点击的是登录或者是注册
			issignin: false
		}
		this._events();
		this._islogin();
	}
	render() {
		let template = handlerbar.compile(userTpl);
		let rs = template(this.userdata)
		$("#user").html(rs);
	}
	_events() {
		$("#user").on('click', 'span[name="login"]', () => {
			$(".box-title").html('登录')
			this.userdata.issignin = false;
		})

		$("#user").on('click', 'span[name="signin"]', () => {
			$(".box-title").html('注册')
			this.userdata.issignin = true;
		})

		//登录和注册的提交
		$("#user").on('click', 'a[name="submit"]', () => {
			this._submit();
		})

		//退出
		$("#user").on('click', 'a[name="quit"]', () => {
			this._quit();
		})
	}

	_quit() {
		let url = '/api/users/layout';
		$.ajax({
			type: 'get',
			url: url,
			success:(result)=> {
				if(result.code === 1){
					this.userdata.username = '';
					this.userdata.islogin = false;
					this.render();	
				}
			},
			error() {
			}
		})
	}
	//发送注册或者登录请求
	_submit() {
		let url = '/api/users/login';
		if (this.userdata.issignin) {
			url = "/api/users/signin";
			//发送注册的请求
			$.ajax({
				type: 'post',
				url: url,
				data: $("#user-form").serialize(),
				success: (result) => {
					alert(result.msg)
				},
				error() {}
			})

		} else {
			//发送登录请求
			$.ajax({
				type: 'post',
				url: url,
				data: $("#user-form").serialize(),
				success: (result, a, xhr) => {
				        if (result.code === 1) {
				          let token = xhr.getResponseHeader("X-ACCESS-TOKEN");
				          localStorage.setItem('token', token);
				          this.userdata.username = result.username;
				          this.userdata.islogin = true;
				          this.render();
				        } else {
				          alert(result.msg);
				        }
				      },
				error() {}
			})
		}

	}
	_islogin(){
		let url = '/api/users/islogin';
		$.ajax({
			type: 'get',
			url: url,
			success:(result)=> {
				if(result.code === 1){
					this.userdata.username = result.username;
					this.userdata.islogin = true;
					this.render();
				}
			},
			error() {
			}
		})
	}
	

}

const userController = new UserController()

export default userController;
